package org.youyun56.gpsserver.common;

import java.lang.reflect.Constructor;

import org.youyun56.gpsserver.ServiceType;
import org.youyun56.gpsserver.command.AbstractService;

public enum MainEngine {
    instance;
    private static ServiceType serviceType;
    private AbstractService server;

    public void start(String args[]) {
        if (args != null && args.length >= 1) {
            String name = args[0];
            if (isValidServiceName(name)) {
                System.out.println(startService(name.toUpperCase()));
            } else {
                System.out.println(String.format("There's no service called", name));
            }
        }
    }

    private String startService(String name) {
        try {
            Constructor<? extends AbstractService> constructor = serviceType.getClazz().getConstructor();
            this.server = constructor.newInstance();
            server.setServiceType(serviceType);
            server.run();
        }
        catch (Exception e) {
            throw new RuntimeException("Could not create instance for serviceType " + serviceType.getClass(), e);
        }
        return "START " + name + " FINISHED !";
    }

    private boolean isValidServiceName(String name) {
        serviceType = ServiceType.findServiceTypeByName(name);
        return serviceType != null;
    }

    public static void main(String[] args) {
        MainEngine.instance.start(args);

    }

    public AbstractService getServer() {
        // TODO Auto-generated method stub
        return server;
    }

    public ServiceType getServiceType() {
        // TODO Auto-generated method stub
        return serviceType;
    }

}
